package net.bingosoft.common.util;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.ecside.table.limit.Filter;
import org.ecside.table.limit.Limit;
import org.ecside.table.limit.Sort;
import org.ecside.util.RequestUtils;

/**
 * 2007-8-17 上午11:15:32
 * Author:yangdongyu(yangdy@bingosoft.net)
 * ReadMe:Ectable的Limit对象的工具类
 * ChangeLog:
 */
public class LimitUtil {
	/**
	 * 从Limit中获取排序语句
	 * @param limit
	 * @return
	 */
	public static String getOrderBy(Limit limit){
		Sort sort = limit.getSort();
		if(sort != null && StringUtils.isNotEmpty(sort.getProperty()) && StringUtils.isNotEmpty(sort.getSortOrder())){
			if(sort.getProperty().equals("_extend")) return "";
			return "order by " + (StringUtils.isEmpty(sort.getAlias()) ? sort.getProperty(): sort.getAlias()) + " " + sort.getSortOrder();
		}else{
			return "";
		}
	}
	/**
	 * 获取排序的属性,返回结果为 属性名 升序或降序,如 name desc,如果取不到排序信息,返回""
	 * @param limit
	 * @return
	 */
	public static String getOrderProperty(Limit limit){
		Sort sort = limit.getSort();
		if(sort != null && StringUtils.isNotEmpty(sort.getProperty()) && StringUtils.isNotEmpty(sort.getSortOrder())){
			if(sort.getProperty().equals("_extend")) return "";
			return (StringUtils.isEmpty(sort.getAlias()) ? sort.getProperty(): sort.getAlias()) + " " + sort.getSortOrder();
		}else{
			return "";
		}
	}

	/**
	 * 获取Limit对象
	 * @param request
	 * @return
	 */
	public static Limit getLimit(HttpServletRequest request){
		return RequestUtils.getLimit(request);
	}
	/**
	 * 获取Limit对象
	 * @param request
	 * @param cTableId Ectable的标识,即tableId的值
	 * @return
	 */
	public static Limit getLimit(HttpServletRequest request,String cTableId){
		return RequestUtils.getLimit(request,cTableId);
	}
	
	/**
	 * 获取过滤Map,map中放的是属性名称与属性值(如果有别名,优先采用别名),可以据此过滤分页查询结果
	 * @return
	 */
	public static Map getFilterMap(Limit limit){
		Map <String, String>property2ValueMap = new HashMap<String, String>();
		if(limit != null && limit.getFilterSet() != null && limit.getFilterSet().getFilters() != null){
			for(Filter f : limit.getFilterSet().getFilters()){
				if(StringUtils.isNotEmpty(f.getValue())){
					property2ValueMap.put(StringUtils.isEmpty(f.getAlias()) ? f.getAlias():f.getProperty(), f.getValue());
				}
			}
		}
		property2ValueMap.remove("_extend");
		return property2ValueMap;
	}
}
